package com.abc.easyclaim;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.abc.bean.Case;
import com.abc.db.DBManager;
import com.abc.tool.Constants;
import com.abc.widget.ListViewAdapter;

public class CaseListActivity  extends Activity implements OnClickListener{
	private static final String TAG = "activity";
	private DBManager mgr;
	private ListView caseListView ;
	private ListViewAdapter listViewAdapter;   
	private List<Map<String, Object>> listItems;//数据
	private long exitTime;
	private int itemid;           //list中被选中项的序号
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_case_list);
		caseListView =(ListView) findViewById(R.id.case_list_view);
		refreshCaseList();
		
		Button createBtn =(Button)findViewById(R.id.case_create);
		createBtn.setOnClickListener(this);
		Button exitBtn =(Button)findViewById(R.id.case_list_exit);
		exitBtn.setOnClickListener(this);
		//动态注册广播
		IntentFilter intentFilter = new IntentFilter();  
	    intentFilter.addAction(Constants.INTENT_REFRESH_CASE_LIST);  
	    registerReceiver(mRefreshBroadcastReceiver, intentFilter);  
	    
		Log.e(TAG, "start onCreate~~~");  
	}
	

	/**
	 * 封装要显示的数据
	 * @return
	 */
	private List<Map<String, Object>> getListItems() {
		mgr = new DBManager(this);
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();   
        List<Case> cases = mgr.queryCases();
		for(int i = 0; i<cases.size(); i++) {  
			Case caze = cases.get(i);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", caze.getId());
            map.put("image", MainApplication.getCarLogoImage(caze.getCarBrand()));               //图片资源   
            map.put("title", caze.getName());              //物品标题   
            map.put("info", "车牌:"+caze.getCarNumber()+"\r\n保单号:"+caze.getInsuranceNumber());     //物品名称   
            listItems.add(map);   
            Log.d("list",caze.getCarBrand());
        }      
        return listItems;   
	}

	
	 
	 @Override  
    protected void onDestroy() {  
        super.onDestroy();  
        unregisterReceiver(mRefreshBroadcastReceiver);
        //应用的最后一个Activity关闭时应释放DB  
        mgr.closeDB();  
        Log.e(TAG, "start onDestory~~~");  
    }  
	
	
	@Override    
	public boolean onKeyDown(int keyCode, KeyEvent event) {   
		
	    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){    
	    	           
		    if((System.currentTimeMillis()-exitTime) > 2000){    
		        Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();                                 
		        exitTime = System.currentTimeMillis();    
		    }    
		    else{ 
		    	exit(); 
		        
		    }              
	        return true; //返回true表示执行结束不需继续执行父类按键响应  
	    }    
	    return super.onKeyDown(keyCode, event);    
	}
	
	private void  exit(){
		MainApplication.saveConfigData();    
    	Log.d("sys", "application exit");
        finish();    
        System.exit(0); 
	}
	// broadcast receiver  
	private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {  
	  
	      @Override  
	      public void onReceive(Context context, Intent intent) {  
	          String action = intent.getAction();  
	          if (action.equals(Constants.INTENT_REFRESH_CASE_LIST))  
	          {  
	              refreshCaseList();  
	          }  
	      }  
	};  
	
	private void refreshCaseList(){
		listItems = getListItems(); 
		listViewAdapter = new ListViewAdapter(this, listItems); //创建适配器   
		caseListView.setAdapter(listViewAdapter);
		//单击事件
		caseListView.setOnItemClickListener(new OnItemClickListener(){ 
            @Override 
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
                    long arg3) { 
                //获得选中项的HashMap对象 
                HashMap<String,Object> map=(HashMap<String, Object>)caseListView.getItemAtPosition(arg2); 
                Intent intent = new Intent(CaseListActivity.this,MetroMenuActivity.class);
                Integer para =(Integer) listItems.get(arg2).get("id");
                intent.putExtra("id", para);
                MainApplication.setCurrentCaseId(para);
                startActivity(intent);
            } 
             
        }); 
		//长按事件
		registerForContextMenu(caseListView);   //为列表注册上下文菜单
		caseListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				System.out.println(arg2);
				itemid = arg2;              //传递第几项被选中
				return false;
			}			
		});	  
        
	}
	
	//创建上下文菜单时触发此方法
    @Override
 	public void onCreateContextMenu(ContextMenu menu, View v,
 			ContextMenuInfo menuInfo) {
 		// TODO Auto-generated method stub
     	getMenuInflater().inflate(R.menu.case_popup_menu, menu);       //添加菜单布局
 		super.onCreateContextMenu(menu, v, menuInfo);
 	}
    
	//上下文菜单的菜单项被单击时触发该方法
    @Override
	public boolean onContextItemSelected(MenuItem item) {
		int menuItem = item.getItemId();
		if (menuItem == R.id.case_reedit) {
			Intent intent = new Intent(CaseListActivity.this,CaseNewActivity.class);
            intent.putExtra("isEdit", true);
            MainApplication.setCurrentCaseId((Integer) listItems.get(itemid).get("id"));
            startActivity(intent);
		} 
		else if (menuItem == R.id.case_delete) {
			mgr.deleteCase((Integer)listItems.get(itemid).get("id"));
			Log.e(TAG, "caseid="+(Integer)listItems.get(itemid).get("id")+" has deleteted!");  
			refreshCaseList();
		} 
		else if (menuItem == R.id.case_exit) {
			Toast.makeText(CaseListActivity.this, "DDD", Toast.LENGTH_LONG);
		}
		return super.onContextItemSelected(item);
	}
    

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.case_create:
			startActivity(new Intent(CaseListActivity.this, CaseNewActivity.class));
			break;
		case R.id.case_list_exit:
			exit();
			break;
		default:
			break;
		}
	}    
	
	 @Override  
	    protected void onStart() {  
	        super.onStart();  
	        Log.e(TAG, "start onStart~~~");  
	    }  
	    @Override  
	    protected void onRestart() {  
	        super.onRestart();  
	        Log.e(TAG, "start onRestart~~~");  
	    }  
	    @Override  
	    protected void onResume() {  
	        super.onResume();  
	        Log.e(TAG, "start onResume~~~");  
	    }  
	    @Override  
	    protected void onPause() {  
	        super.onPause();  
	        Log.e(TAG, "start onPause~~~");  
	    }  
	    @Override  
	    protected void onStop() {  
	        super.onStop();  
	        Log.e(TAG, "start onStop~~~");  
	    }  
}
